package com.example.springcloud.controller;

import com.example.springcloud.entities.CommonResult;
import com.example.springcloud.entities.Payment;
import com.example.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2024-01-28
 * Time: 17:11
 */

@RestController
@Slf4j
@RequestMapping("/consumer")
public class OrderController {

//    public static final String PAYMENT_URL = "http://localhost:8001";单机写死
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";// 集群只认服务名称，不指定端口

    @Resource
    private RestTemplate restTemplate;// 用于调用其它网络端口的服务

    @Resource
    private DiscoveryClient discoveryClient;


    @Resource
    private LoadBalancer loadBalancer;// 自定义的负载均衡算法


    @GetMapping("/payment/create")
    public CommonResult create(Payment payment) {
//        url, 传入参数， 返回类型
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }


    @GetMapping("/payment/get/{id}")
    public CommonResult getPayment(@PathVariable("id") Long id) {
//        url, 返回类型
        // 返回对象为响应体中数据转化成的对象，基本上可以理解为 Json
        CommonResult object = restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
        return object;
    }

    @GetMapping("/payment/getForEntity/{id}")
    public CommonResult getPayment2(@PathVariable("id") Long id) {
        // 返回对象为 ResponseEntity，包含响应中的一些重要的信息，比如响应头，响应状态码，响应体等
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
        // 请求成功
        if (entity.getStatusCode().is2xxSuccessful()) {
            return entity.getBody();
        }

        return new CommonResult(444, "操作失败");
    }


    @GetMapping("/payment/lb")
    public String getPaymentLB() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances == null || instances.isEmpty()) {
            return null;
        }
        // 选出某个微服务
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        log.info(uri.toString());


        return uri.toString();
    }


    // zipkin + sleuth
    @GetMapping("/payment/zipkin")
    public String paymentZipkin() {
        String res =  restTemplate.getForObject(PAYMENT_URL + "/payment/zipkin", String.class);

        return res;
    }

}
